package com.example.pclimb.ui.admin;

import android.app.AlertDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;

import com.example.pclimb.R;
import com.example.pclimb.databinding.ActivityGuiderApplicationDetailBinding;
import com.example.pclimb.model.GuideImage;
import com.example.pclimb.model.User;
import com.example.pclimb.ui.adapters.CertificateImageAdapter;
import com.example.pclimb.viewmodel.GuideImageViewModel;
import com.example.pclimb.viewmodel.UserViewModel;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

/**
 * 向导申请详情页面
 */
public class GuiderApplicationDetailActivity extends AppCompatActivity {

    private static final String TAG = "GuiderApplicationDetail";
    
    private ActivityGuiderApplicationDetailBinding binding;
    private UserViewModel userViewModel;
    private GuideImageViewModel guideImageViewModel;
    private CertificateImageAdapter imageAdapter;
    private User applicant;
    private int userId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityGuiderApplicationDetailBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        // 设置工具栏
        setSupportActionBar(binding.toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        binding.toolbar.setNavigationOnClickListener(v -> onBackPressed());

        // 初始化ViewModel
        userViewModel = new ViewModelProvider(this).get(UserViewModel.class);
        guideImageViewModel = new ViewModelProvider(this).get(GuideImageViewModel.class);

        // 获取申请用户ID
        userId = getIntent().getIntExtra("USER_ID", -1);
        if (userId == -1) {
            Toast.makeText(this, R.string.error_loading_data, Toast.LENGTH_SHORT).show();
            finish();
            return;
        }

        // 设置图片适配器
        setupImageRecyclerView();

        // 加载申请详情
        loadApplicationDetails();

        // 设置按钮点击事件
        binding.btnApprove.setOnClickListener(v -> showApproveConfirmDialog());
        binding.btnReject.setOnClickListener(v -> showRejectConfirmDialog());
    }

    /**
     * 设置证书图片RecyclerView
     */
    private void setupImageRecyclerView() {
        imageAdapter = new CertificateImageAdapter(this);
        binding.recyclerCertificateImages.setLayoutManager(new GridLayoutManager(this, 3));
        binding.recyclerCertificateImages.setAdapter(imageAdapter);
        
        // 设置图片点击事件
        imageAdapter.setOnImageClickListener(new CertificateImageAdapter.OnImageClickListener() {
            @Override
            public void onImageClick(GuideImage image, int position) {
                // 查看大图
                showLargeImage(image);
            }

            @Override
            public void onDeleteClick(GuideImage image, int position) {
                // 管理员不允许删除图片，所以这里不做任何操作
            }
        });
    }

    /**
     * 加载申请详情
     */
    private void loadApplicationDetails() {
        // 显示加载进度条
        binding.progressBar.setVisibility(View.VISIBLE);
        
        // 加载用户信息
        userViewModel.getUserById(userId).observe(this, user -> {
            binding.progressBar.setVisibility(View.GONE);
            
            if (user != null) {
                applicant = user;
                
                // 更新UI
                binding.tvUsername.setText(user.getUsername());
                
                // 设置手机号码
                String phoneNumber = user.getPhone() != null ? user.getPhone() : user.getPhoneNumber();
                binding.tvPhone.setText(phoneNumber != null && !phoneNumber.isEmpty() 
                        ? phoneNumber : "未设置手机号");
                
                // 设置邮箱
                binding.tvEmail.setText(user.getEmail() != null && !user.getEmail().isEmpty() 
                        ? user.getEmail() : "未设置邮箱");
                
                // 设置申请日期
                long applicationTime = System.currentTimeMillis();
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault());
                binding.tvApplicationDate.setText(dateFormat.format(new Date(applicationTime)));
                
                // 设置登山经验
                binding.tvExperience.setText(user.getExperience() != null ? user.getExperience() : "无");
                
                // 设置证书信息
                binding.tvCertification.setText(user.getCertification() != null ? user.getCertification() : "无");
                
                // 加载证书图片
                loadCertificateImages(user.getId());
            } else {
                Toast.makeText(this, R.string.error_loading_data, Toast.LENGTH_SHORT).show();
                finish();
            }
        });
    }
    
    /**
     * 加载证书图片
     */
    private void loadCertificateImages(int userId) {
        guideImageViewModel.getUserImages(userId).observe(this, images -> {
            if (images != null && !images.isEmpty()) {
                binding.recyclerCertificateImages.setVisibility(View.VISIBLE);
                binding.tvNoCertificates.setVisibility(View.GONE);
                imageAdapter.setImages(images);
            } else {
                binding.recyclerCertificateImages.setVisibility(View.GONE);
                binding.tvNoCertificates.setVisibility(View.VISIBLE);
            }
        });
    }
    
    /**
     * 显示大图
     */
    private void showLargeImage(GuideImage image) {
        // 创建对话框显示大图
        View view = getLayoutInflater().inflate(R.layout.dialog_image_preview, null);
        
        // 加载图片（同样是使用Glide）
        // 这部分代码你已经在ApplyGuideActivity中实现过，可以直接复用
        
        new AlertDialog.Builder(this)
                .setTitle(R.string.view_certificate)
                .setView(view)
                .setPositiveButton(R.string.ok, null)
                .show();
    }
    
    /**
     * 显示批准确认对话框
     */
    private void showApproveConfirmDialog() {
        new AlertDialog.Builder(this)
                .setTitle(R.string.approve_application)
                .setMessage(R.string.approve_confirm)
                .setPositiveButton(R.string.approve, (dialog, which) -> approveApplication())
                .setNegativeButton(R.string.cancel, null)
                .show();
    }
    
    /**
     * 显示拒绝确认对话框
     */
    private void showRejectConfirmDialog() {
        new AlertDialog.Builder(this)
                .setTitle(R.string.reject_application)
                .setMessage(R.string.reject_confirm)
                .setPositiveButton(R.string.reject, (dialog, which) -> rejectApplication())
                .setNegativeButton(R.string.cancel, null)
                .show();
    }
    
    /**
     * 批准向导申请
     */
    private void approveApplication() {
        if (applicant != null) {
            // 显示进度条
            binding.progressBar.setVisibility(View.VISIBLE);
            binding.btnApprove.setEnabled(false);
            binding.btnReject.setEnabled(false);
            
            try {
                // 更新用户信息
                applicant.setUserType(User.TYPE_GUIDE);
                applicant.setGuideApplication(User.APPLICATION_APPROVED);
                applicant.setGuideApproved(true);
                
                // 更新用户信息
                userViewModel.updateUser(applicant);
                
                // 显示成功提示
                Toast.makeText(this, R.string.approve_success, Toast.LENGTH_SHORT).show();
                
                // 关闭页面
                finish();
            } catch (Exception e) {
                Log.e(TAG, "批准申请出错: ", e);
                binding.progressBar.setVisibility(View.GONE);
                binding.btnApprove.setEnabled(true);
                binding.btnReject.setEnabled(true);
                Toast.makeText(this, "批准申请失败，请稍后重试", Toast.LENGTH_SHORT).show();
            }
        }
    }
    
    /**
     * 拒绝向导申请
     */
    private void rejectApplication() {
        if (applicant != null) {
            // 显示进度条
            binding.progressBar.setVisibility(View.VISIBLE);
            binding.btnApprove.setEnabled(false);
            binding.btnReject.setEnabled(false);
            
            try {
                // 更新用户信息
                applicant.setGuideApplication(User.APPLICATION_REJECTED);
                applicant.setGuideApproved(false);
                
                // 更新用户信息
                userViewModel.updateUser(applicant);
                
                // 显示成功提示
                Toast.makeText(this, R.string.reject_success, Toast.LENGTH_SHORT).show();
                
                // 关闭页面
                finish();
            } catch (Exception e) {
                Log.e(TAG, "拒绝申请出错: ", e);
                binding.progressBar.setVisibility(View.GONE);
                binding.btnApprove.setEnabled(true);
                binding.btnReject.setEnabled(true);
                Toast.makeText(this, "拒绝申请失败，请稍后重试", Toast.LENGTH_SHORT).show();
            }
        }
    }
} 